package enterprise.web.tookit.account;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.NonUniqueResultException;
import javax.persistence.Query;

import enterprise.web.tookit.generic.GenericDaoImpl;

/**
 * 
 * @author regisrocha
 * 
 */
public class AccountDaoImpl extends GenericDaoImpl implements AccountDao {

	/**
	 * Serial version
	 */
	private static final long serialVersionUID = 7149107802907733126L;

	/**
	 * Attribute for entity manager
	 */
	private EntityManager entityManager;

	public AccountDaoImpl(EntityManager em) {
		super(em);
		entityManager = super.getEntityManager();
	}

	@Override
	public final Account login(Account account) throws AccountException {
		final Query query = entityManager
				.createQuery("SELECT a FROM Account a WHERE username = :username AND password = :password");
		query.setParameter("username", account.getUsername());
		query.setParameter("password", account.getPassword());

		try {
			return (Account) query.getSingleResult();
		} catch (NoResultException e) {
			throw new AccountException("there is no result ", e);
		} catch (NonUniqueResultException e) {
			throw new AccountException("more than one result", e);
		} catch (Exception e) {
			throw new AccountException(e);
		}
	}

	@Override
	public Account updateAccount(Account account) throws AccountException {
		try {
			return entityManager.merge(account);
		} catch (Exception e) {
			throw new AccountException(e);
		}
	}

	@Override
	public boolean usernameModified(Account account) {
		try {
			final Query query = entityManager
					.createQuery("SELECT a FROM Account a WHERE username = :username AND id = :id");
			query.setParameter("username", account.getUsername());
			query.setParameter("id", account.getId());
			query.getSingleResult();
		} catch (Exception e) {
			return true;
		}

		return false;
	}
}
